package Singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by wangyg 
 * on 2017/6/13 19:16
 */
public class LazyLoadSingleton {
	private static LazyLoadSingleton instance;

	private LazyLoadSingleton() {
	}

	//增加同步synchronized，避免多线程时错误
	public static synchronized LazyLoadSingleton getInstance() {
		if (instance == null) {//懒汉式

			//创建实例之前可能会有一些准备性的耗时工作
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			instance = new LazyLoadSingleton();
		}
		return instance;
	}

	public static void main(String[] args) throws InterruptedException {
		//		Thread[] ts = new Thread[10];
		//		for (int i = 0; i < 10; i++) {
		//			Thread thread = new Thread() {
		//				public void run() {
		//
		//					System.out.println(
		//							Thread.currentThread().getName() + ":" + LazyLoadSingleton.getInstance().hashCode());
		//
		//				}
		//			};
		//			//			Thread.sleep(600);
		//			ts[i] = thread;
		//		}
		//		for (int i = 0; i < ts.length; i++) {
		//			ts[i].start();
		//		}

		Class<?> aClass = null;
		try {
			aClass = Class.forName("Singleton.LazyLoadSingleton");
			LazyLoadSingleton l = (LazyLoadSingleton) aClass.newInstance();
			System.out.println(LazyLoadSingleton.class.newInstance().hashCode());
			System.out.println(l.hashCode());
			Constructor<?> declaredConstructor = aClass.getDeclaredConstructor();
			System.out.println(declaredConstructor.newInstance().hashCode());

			//			Constructor<?>[] cons = aClass.getDeclaredConstructors();
			//			for (Constructor<?> con : cons) {
			//				con.setAccessible(true);
			//				con.
			//			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

	}

}
